package com.lechi.web.server.connect;

import com.lechi.iot.android.channel.IIotTcpChannel;
import com.lechi.iot.android.device.IotTcpDeviceChannel;
import com.lechi.iot.netty.utils.NettyCacheUtils;
import com.lechi.web.framework.util.GuavaCacheUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * Android报文 服务端链接管理器,处理接受数据
 */
@Slf4j
@Sharable
public class IotTcpServerConnect extends ChannelInboundHandlerAdapter {


    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        ctx.fireChannelActive();
        if (Objects.nonNull(channel) && Objects.nonNull(channel.remoteAddress())) {
            IIotTcpChannel tcpChannel = new IotTcpDeviceChannel(channel);
            String address = channel.remoteAddress().toString();
            log.error("android服务和设备地址：{} 建立链接", address);
            NettyCacheUtils.put(address, tcpChannel);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        ctx.fireChannelInactive();
        Channel channel = ctx.channel();
        if (Objects.nonNull(channel) && Objects.nonNull(channel.remoteAddress())) {
            String address = channel.remoteAddress().toString();
            IIotTcpChannel tcpChannel = NettyCacheUtils.get(address, IIotTcpChannel.class);
            log.error("android 服务端和设备地址：{} 断开链接！", address);
            if (tcpChannel != null && tcpChannel.getDeviceSn() != null) {
                log.error("android 服务端序列号:{}和设备地址：{} 断开链接！", tcpChannel.getDeviceSn(), address);
                String androidDeviceSn = tcpChannel.getDeviceSn();
                NettyCacheUtils.remove(address);
                GuavaCacheUtil.getBiDeviceSnAndIPMap().remove(androidDeviceSn);
            }
            ctx.pipeline().remove(ctx.handler());
            ctx.deregister();
            ctx.close();
        }
    }
}
